package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private Client client;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCode(String phone) throws Exception {
        //todo 判断redis中key是否存在 判断是否重复发送
        //定义存储redis的key  自定义常量+手机号
        String key= RedisConstant.APP_LOGIN_PREFIX+phone;
        //判断redis内是否有key 设置key的有效期 根据key是否存在，判断是否过期
        Boolean hasKey = redisTemplate.hasKey(key);

        if (hasKey) {
            //key存在，则没有过期 抛出验证码频繁异常
            throw  new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }

        //todo 发送短信
        //生成随机的四位code
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code+=random.nextInt(10);
        }
        //创建短信发送对象
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        //设置发送手机
        sendSmsRequest.setPhoneNumbers(phone);
        //设置发送签名
        sendSmsRequest.setSignName("阿里云短信测试");
        //设置发送模板
        sendSmsRequest.setTemplateCode("SMS_154950909");
        //设置模板参数
        sendSmsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
        //调用sendSms方法，传递sendSmsRequest对象 发送
        client.sendSms(sendSmsRequest);

        //todo 将key 和 验证码 存储到redis中
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        //验证码空值检验
        if (ObjectUtils.isEmpty(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //检查redis中的验证码是否过期
        String key = (String) redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone());
        if (ObjectUtils.isEmpty(key)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //对比输入的验证码和redis验证码，检查验证码是否正确
        if (!loginVo.getCode().equalsIgnoreCase(key)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        //通过手机号检查是否有用户  无用户则信则新增注册
        if (userInfo==null) {
            UserInfo reUser = new UserInfo();
            reUser.setPhone(loginVo.getPhone());
            reUser.setNickname("佚名"+loginVo.getPhone().substring(5));
            reUser.setStatus(BaseStatus.ENABLE);
            userInfoService.save(reUser);
        }
        UserInfo userInfo1 = userInfoService.getOne(userInfoLambdaQueryWrapper);
        //检查账号状态是否封禁
        if (userInfo1.getStatus()== BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        return JwtUtil.createToken(userInfo.getId(),loginVo.getPhone());

    }
}
